# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: FastApi事件监听
"""

from typing import Callable
from fastapi import FastAPI

from core.db.mysql import init_mysql
from core.cache import redis


def create_start_app_handler(app: FastAPI) -> Callable:
    """
    FastApi 启动完成事件
    :param app: FastAPI
    :return: start_app
    """
    async def start_app() -> None:
        # APP启动完成后触发
        # Redis 缓存
        cache = await redis.init_cache()
        app.state.cache = cache
        # 验证码缓存
        code = await redis.init_code()
        app.state.code = code

        # 初始化 数据库
        await init_mysql(app)

    return start_app


def create_stop_app_handler(app: FastAPI) -> Callable:
    """
    FastApi 停止事件
    :param app: FastAPI
    :return: stop_app
    """
    async def stop_app() -> None:

        # APP关闭时触发
        await app.state.cache.close()
        await app.state.code.close()

    return stop_app
